package com.example.service.impl;

import com.example.common.CustomException;
import com.example.dao.FavDao;
import com.example.dao.GoodsDao;
import com.example.entity.Fav;
import com.example.entity.Goods;
import com.example.service.FavService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 收藏服务实现类
 */
@Service
public class FavServiceImpl implements FavService {

    @Resource
    private FavDao favDao;
    
    @Resource
    private GoodsDao goodsDao;

    @Override
    public PageInfo<Fav> getFavList(Integer pageNum, Integer pageSize, String key, String memberid) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", key);
        map.put("memberid", memberid);
        
        PageHelper.startPage(pageNum, pageSize);
        List<Fav> list = favDao.selectAll(map);
        
        // 填充商品信息
        for (Fav fav : list) {
            Goods goods = goodsDao.findById(fav.getGoodsid());
            fav.setGoodsname(goods.getName());
            fav.setGoods(goods);
        }
        
        return new PageInfo<>(list);
    }

    @Override
    public String addOrCancelFav(Fav fav) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("memberid", fav.getMemberid());
        map.put("goodsid", fav.getGoodsid());
        
        List<Fav> list = favDao.selectAll(map);
        if (list.size() == 0) {
            // 如果不存在，则添加收藏
            favDao.add(fav);
            return null; // 没有消息表示添加成功
        } else {
            // 如果已存在，则取消收藏
            favDao.delete(list.get(0).getId());
            return "已取消收藏";
        }
    }

    @Override
    public void deleteFav(int id) {
        favDao.delete(id);
    }
} 